package com.monkeygroup.mygoplus.ecchat.ui.contact.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/1/20.
 */
public class ContactRecord {
    public static final String TABLE_NAME = "contacts";
    public static final String COLUMN_CONTENT = "content";
    public static final String COLUMN_LATEST_TIME = "time";
    public static final String COLUMN_TOTAL_COUNT = "count";

    public static final String CONTACT_TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " ("
            + COLUMN_CONTENT + " VARCHAR(100) PRIMARY KEY, "
            + COLUMN_LATEST_TIME + " VARCHAR(100), "
            + COLUMN_TOTAL_COUNT + " INT );";

    private MGDbHelper helper;

    public ContactRecord(Context context) {
        helper = MGDbHelper.getInstance(context);
    }

    public void addRecord(Map<String, Object> map) {
        SQLiteDatabase db = helper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_CONTENT, (String) map.get(COLUMN_CONTENT));
        values.put(COLUMN_LATEST_TIME, (String) map.get(COLUMN_LATEST_TIME));
        values.put(COLUMN_TOTAL_COUNT, (int) map.get(COLUMN_TOTAL_COUNT));

        if (db.isOpen()) {
            db.replace(TABLE_NAME, null, values);
        }

        db.close();
    }

    public void deleteAllRecords() {
        SQLiteDatabase db = helper.getWritableDatabase();
        if (db.isOpen()) {
            db.delete(TABLE_NAME, null, null);
        }

        db.close();
    }

    public List<Map<String, Object>> getRecords(int a, int b) {
        List<Map<String, Object>> list = new ArrayList<>();
        String start = String.valueOf(a * b);
        String size = String.valueOf(b);

        SQLiteDatabase db = helper.getReadableDatabase();
        if (db.isOpen()) {
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME
                    + " order by " + COLUMN_LATEST_TIME + " desc" + " limit " + start + "," + size, null);

            while (cursor.moveToNext()) {
                String content = cursor.getString(cursor.getColumnIndex(COLUMN_CONTENT));
                String time = cursor.getString(cursor.getColumnIndex(COLUMN_LATEST_TIME));
                int count = cursor.getInt(cursor.getColumnIndex(COLUMN_TOTAL_COUNT));

                Map<String, Object> map = new HashMap<>();
                map.put(COLUMN_CONTENT, content);
                map.put(COLUMN_LATEST_TIME, time);
                map.put(COLUMN_TOTAL_COUNT, count);

                list.add(map);
            }

            db.close();
        }

        return list;
    }

}
